package asteroid

import (
	"fmt"

	"gddgame.cc/galaxy/utils/def"
)

type Socket interface {
	Nodes() []string
	Get(node string) chan def.Stream
	Connect(node string) error
	IsConnect(node string) bool
	Listen(node string) error
	Close() error
	Bind(layer func(msg []byte), close <-chan struct{})
}

type LocalSocket struct {
	layer func(msg []byte)
	c     chan def.Stream
	close <-chan struct{}
}

func (l *LocalSocket) Nodes() []string {
	return []string{}
}

func (l *LocalSocket) Get(node string) chan def.Stream {
	return l.c
}

func (l *LocalSocket) Connect(node string) error {
	return nil
}

func (l *LocalSocket) IsConnect(node string) bool {
	return true
}

func (l *LocalSocket) Listen(node string) error {
	go func() {
		for {
			select {
			case s := <-l.c:
				b, err := s.Payload()
				if err != nil {
					s.Release()
					continue
				}
				l.layer(b)
				s.Release()
			case <-l.close:
				goto Clean
			}
		}
	Clean:
		fmt.Println("clean")
	}()
	return nil
}

func (l *LocalSocket) Close() error {
	return nil
}

func (l *LocalSocket) Bind(layer func(msg []byte), close <-chan struct{}) {
	l.layer = layer
	l.close = close
	l.c = make(chan def.Stream)
}
